<template>
  <div class="user-management" v-if="user && user.role === 'admin'">
    <el-card>
      <template #header>
        <span>用户管理</span>
      </template>
      <el-table :data="users" style="width: 100%">
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="role" label="角色" width="180"></el-table-column>
        <el-table-column align="right">
          <template #header>
            <el-button type="primary" @click="addUser">添加新用户</el-button>
          </template>
          <template #default="scope">
            <el-button size="mini" @click="editUser(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑用户对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isNewUser ? '新增用户' : '编辑用户'"
    >
      <el-form :model="editingUser">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="computedUsername" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" v-if="isNewUser">
          <el-input
              v-model="computedPassword"
              :type="showPassword ? 'text' : 'password'"
              autocomplete="off"
          ></el-input>
          <img
              src="../img/password.png"
              alt="查看密码"
              style="margin-left: 10px; cursor: pointer; width: 20px; height: 20px;"
              @click="showPassword = !showPassword"
          />
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-select v-model="computedRole" placeholder="请选择角色">
            <el-option label="经理" value="manager"></el-option>
            <el-option label="普通用户" value="user"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {getUsers, createUser, updateUser, deleteUser} from '@/api/users';

export default {
  data() {
    return {
      users: [],
      editingUser: null,
      dialogVisible: false,
      formLabelWidth: '100px',
      user: null,
      isNewUser: false,
      showPassword: false,
      isLoading: false, // 添加加载状态
    };
  },
  computed: {
    computedUsername: {
      get() {
        return this.editingUser ? this.editingUser.username : '';
      },
      set(value) {
        if (this.editingUser) this.editingUser.username = value;
      }
    },
    computedPassword: {
      get() {
        return this.editingUser ? this.editingUser.password : '';
      },
      set(value) {
        if (this.editingUser) this.editingUser.password = value;
      }
    },
    computedRole: {
      get() {
        return this.editingUser ? this.editingUser.role : '';
      },
      set(value) {
        if (this.editingUser) this.editingUser.role = value;
      }
    }
  },
  methods: {
    async fetchUsers() {
      this.isLoading = true; // 开始加载
      try {
        const response = await getUsers();
        this.users = response.data;
      } catch (error) {
        console.error('获取用户列表失败:', error);
      } finally {
        this.isLoading = false; // 加载完成
      }
    },
    async addUser() {
      this.isNewUser = true;
      this.editingUser = {username: '', password: '', role: 'user'};
      this.dialogVisible = true;
    },
    async editUser(user) {
      if (user) {
        this.isNewUser = false;
        this.editingUser = {...user}; // 使用深拷贝
        this.dialogVisible = true;
      } else {
        console.error('尝试编辑一个未定义的用户。');
      }
    },
    async handleSubmit() {
      try {
        if (this.editingUser.id) {
          // 如果用户存在 ID，则更新用户
          await updateUser(this.editingUser.id, this.editingUser);
        } else {
          // 如果用户没有 ID，则创建新用户
          await createUser(this.editingUser);
        }
        // 重新获取用户列表
        await this.fetchUsers();
        this.cancelEdit();
      } catch (error) {
        console.error('提交编辑失败:', error);
      }
    },
    async deleteUser(userId) {
      try {
        await deleteUser(userId);
        // 重新获取用户列表
        await this.fetchUsers();
      } catch (error) {
        console.error('删除用户失败:', error);
      }
    },
    cancelEdit() {
      this.editingUser = null;
      this.dialogVisible = false;
      this.isNewUser = false;
      this.showPassword = false;
    }
  },
  mounted() {
    this.fetchUsers();
    // 假设在登录成功后，用户信息存储在localStorage中
    this.user = JSON.parse(localStorage.getItem('user')) || null;
  }
};
</script>

<style scoped>
.user-management {
  padding: 20px;
}

:deep(.el-form-item .el-input__inner) {
  width: calc(100% - 50px);
}

:deep(.el-form-item img) {
  position: absolute;
  right: 20px; /* 调整图标的右侧距离 */
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}
</style>